package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.InventoryMasterAdapter;
import biznussoft.fieldservice360.listeners.InventoryListener;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.InventoryModel;
import biznussoft.fieldservice360.model.SiteModel;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class WarehouseFragment  extends BaseFragment implements OnItemClickListener {
	RestClient client;
	static ArrayList<InventoryModel> InventoryList;
	static ArrayList<SiteModel> InventorySubList;
	static HashMap<String, ArrayList<SiteModel>>  inventorySiteList;
	InventoryListener listener;
	private ListView lv;                                                                                       
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.inventory, null);
	}         

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);


		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (InventoryListener) (activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		lv.setOnItemClickListener(this);
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);

		Task task = new Task();
		task.execute();        

	}

	class Task extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			retriveLeads();
			return null;
		}

	}

	public void retriveLeads()        
	{
		try{
//			String accounts = "SELECT Name,Id,FConnect__Description__c,FConnect__Geo_Location__c,(SELECT Name,Id,FConnect__Warehouses__c,FConnect__Account_Name__c,FConnect__City__c,FConnect__Country__c,FConnect__Email__c,FConnect__Site_Fax__c,FConnect__Site_Phone__c,FConnect__State__c,FConnect__Street__c,FConnect__Web_site__c,FConnect__Zip__c FROM FConnect__Sites__r) FROM FConnect__Warehouses__c";
			String accounts = "SELECT Name,Id,FConnect__Description__c,(SELECT Name,Id,FConnect__Warehouses__c,FConnect__Account_Name__c,FConnect__City__c,FConnect__Country__c,FConnect__Email__c,FConnect__Site_Fax__c,FConnect__Site_Phone__c,FConnect__State__c,FConnect__Street__c,FConnect__Web_site__c,FConnect__Zip__c FROM FConnect__Sites__r) FROM FConnect__Warehouses__c";
			Log.i("TPT","SOQL is     :"+accounts);

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						Log.i("TPT", "Response is   :" + result);
						JSONObject jsonObject1 = new JSONObject(result         
								.toString());
						Log.i("NCS",
								"jsonobject1  is  :" + jsonObject1.length());

						JSONArray jsonArray = jsonObject1
								.getJSONArray("records");

						InventoryList = new ArrayList<InventoryModel>();
						
						inventorySiteList = new HashMap<String, ArrayList<SiteModel>>();
						Gson _gson = new Gson();
						for (int i = 0; i < jsonArray.length(); i++) {
							
							InventorySubList = new ArrayList<SiteModel>();
							
				if (!jsonArray.isNull(i)) {
								InventoryModel bean = _gson.fromJson(jsonArray.getString(i),InventoryModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								
								JSONObject siteObject = jsonArray.getJSONObject(i);
								

								if (siteObject.getJSONObject("FConnect__Sites__r") != null) {

						JSONArray siteArray = siteObject.getJSONObject("FConnect__Sites__r").getJSONArray("records");
								
									
									for (int j = 0; j < siteArray.length(); j++) {
										if (!siteArray.isNull(j)) {
											SiteModel bean1 = _gson.fromJson(
													siteArray.getString(j),
													SiteModel.class);
											InventorySubList.add(bean1);
										}
										
									}
									inventorySiteList.put(ID,InventorySubList);       
									InventoryList.add(bean);
								}
							}

						}

						showRecords();

					} catch (Exception e) {
						
						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					/*  Toast.makeText(MainActivity.this,
                               MainActivity.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
                               Toast.LENGTH_LONG).show();*/
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	}


	public void showRecords(){
		InventoryMasterAdapter adapter = new InventoryMasterAdapter(getActivity(),InventoryList);
		lv.setAdapter(adapter);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		setHasOptionsMenu(false);
		listener.onWarehouseClicked(position);
	}

	
}

